﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SevenZip;
using System.Reflection;
using Microsoft.Win32;
using Autounpacker.Properties;

namespace Autounpacker
{
    public partial class Form1 : Form
    {
        UnPacker no1 = new UnPacker();
        public Form1()
        {
            InitializeComponent();
        }

        #region Startup
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Visible = false;
            loadsettings();
        }

        private void loadsettings()
        {
            Settings.Default.Reload();

            textinputfolderMenuitem.Text = Settings.Default.infolder;
            inputfolderfilesystemwatcher.Path = Settings.Default.infolder;
            textoutputfolderMenuitem.Text = Settings.Default.outfolder;

            deletefileafterextractMenuitem.Checked = Settings.Default.deleteonunpack;
            extractMenuitem.Checked = Settings.Default.enabled;
        }

        #endregion

        #region Main function
        private void inputfolder_filecreated(object sender, System.IO.FileSystemEventArgs e)
        {
            if (Autounpacker.Properties.Settings.Default.enabled)
            {
                if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Changed)
                {
                    try
                    {
                        try
                        {
                            FileStream fs = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.None);
                            fs.Close();
                        }
                        catch (Exception)
                        {

                        }
                        inputfolderfilesystemwatcher.EnableRaisingEvents = false;
                        notifyicon.ShowBalloonTip(1000, "File found", "File found, not in use, attempting unpack", ToolTipIcon.Info);
                        string folder = e.FullPath.Substring(0, e.FullPath.LastIndexOf("\\")) + (e.FullPath.Substring(e.FullPath.LastIndexOf("\\"), e.FullPath.LastIndexOf(".") - e.FullPath.LastIndexOf("\\")).Trim().Replace(".", ""));
                        no1.Unpack(e.FullPath, folder);
                        if (Autounpacker.Properties.Settings.Default.deleteonunpack)
                        {
                            File.Delete(e.FullPath);
                        }
                        inputfolderfilesystemwatcher.EnableRaisingEvents = true;
                    }
                    catch (Exception jaja)
                    {
                        MessageBox.Show(jaja.Message);
                        inputfolderfilesystemwatcher.EnableRaisingEvents = true;
                    }
                }
            }
        }

        #endregion

        #region Folderinputs

        private void textinputfolder_update(object sender, EventArgs e)
        {
            try
            {
                inputfolderfilesystemwatcher.Path = textinputfolderMenuitem.Text;
                Settings.Default.infolder = textinputfolderMenuitem.Text;
            }
            catch (Exception)
            {
            }
        }

        private void textoutputfolder_update(object sender, EventArgs e)
        {
            try
            {
                Settings.Default.outfolder = textoutputfolderMenuitem.Text;
            }
            catch (Exception)
            {
            }
        }

        private void browseforinputfolder(object sender, EventArgs e)
        {
            DialogResult jaja = inputfolderbrowserdialog.ShowDialog();
            if (jaja == DialogResult.OK)
            {
                textinputfolderMenuitem.Text = inputfolderbrowserdialog.SelectedPath;
                inputfolderfilesystemwatcher.Path = textinputfolderMenuitem.Text;
                Settings.Default.infolder = textinputfolderMenuitem.Text;
            }
        }

        private void browseforoutputfolder(object sender, EventArgs e)
        {
            DialogResult jaja = outputfolderbrowserdialog.ShowDialog();
            if (jaja == DialogResult.OK)
            {
                textoutputfolderMenuitem.Text = outputfolderbrowserdialog.SelectedPath;
                Settings.Default.outfolder= textinputfolderMenuitem.Text;
            }
        }
        #endregion

        #region Other items
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings.Default.Save();   
            this.Close();
        }
        #endregion

        #region Settings

        private void startWithWindowsToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Default.bootstart = startwithwindowsMenuitem.Checked;
            if (Settings.Default.bootstart)
            {
                SetAutoStart("Autounpacker", Assembly.GetExecutingAssembly().Location);
            }
            else
            {
                UnSetAutoStart("Autounpacker");
            }
        }

        private void deleteonunpack(object sender, EventArgs e)
        {
            Settings.Default.deleteonunpack = deletefileafterextractMenuitem.Checked;
        }        
        
        private void setenabled(object sender, EventArgs e)
        {
            Settings.Default.enabled = extractMenuitem.Checked;
        }        
        
        private void toggleenabled(object sender, MouseEventArgs e)
        {
            bool action = true;
            if ((Settings.Default.enabled) && action && e.Button == MouseButtons.Left)
            {
                extractMenuitem.Checked = false;
                action = false;
                notifyicon.ShowBalloonTip(1, "Disabled", "Monitoring and extraction disabled", ToolTipIcon.Info);
            }
            else if ((!Settings.Default.enabled) && action && e.Button == MouseButtons.Left)
            {
                extractMenuitem.Checked = true;
                action = true;
                notifyicon.ShowBalloonTip(1, "Enabled", "Monitoring and extraction enabled", ToolTipIcon.Info);
            }
        }

        #endregion

        #region Autostart

        private const string RUN_LOCATION = @"Software\Microsoft\Windows\CurrentVersion\Run";

        

        /// <summary>
        /// Sets the autostart value for the assembly.
        /// </summary>
        /// <param name="keyName">Registry Key Name</param>
        /// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
        public static void SetAutoStart(string keyName, string assemblyLocation)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
            key.SetValue(keyName, assemblyLocation);
        }

        /// <summary>
        /// Returns whether auto start is enabled.
        /// </summary>
        /// <param name="keyName">Registry Key Name</param>
        /// <param name="assemblyLocation">Assembly location (e.g. Assembly.GetExecutingAssembly().Location)</param>
        public static bool IsAutoStartEnabled(string keyName, string assemblyLocation)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION);
            if (key == null)
                return false;

            string value = (string)key.GetValue(keyName);
            if (value == null)
                return false;

            return (value == assemblyLocation);
        }

        /// <summary>
        /// Unsets the autostart value for the assembly.
        /// </summary>
        /// <param name="keyName">Registry Key Name</param>
        public static void UnSetAutoStart(string keyName)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
            try
            {
                key.DeleteValue(keyName);
            }
            catch
            {
            }
        }
        #endregion

        private void aboutMenuitem_Click(object sender, EventArgs e)
        {
            aboutbox ost = new aboutbox();
            ost.ShowDialog();
        }



    }
}
